package domain;

import interfaces.IDataFiles;
import interfaces.IGameManagement;
import interfaces.ILoginManagement;
import interfaces.IPlayerManagement;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Vector;

import valueObjects.game.Player;
import exception.game.SaveFileNotFoundException;
import exception.login.AlreadyLoggedInException;
import exception.login.NotLoggedInException;

/**
 * This class is for managing the login of the players.
 */
public class LoginManagement extends UnicastRemoteObject implements ILoginManagement {
	
	private static final long serialVersionUID = 1L;
	
	private IPlayerManagement pManager;
	
	private Vector<Player> loggedInPlayers = new Vector<Player>();

	private IDataFiles dataFiles;
	
	/**
	 * Constructor with the registered players
	 * @param players
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	public LoginManagement(IPlayerManagement p, IDataFiles data) throws RemoteException{
		this.pManager = p;
		this.dataFiles = data;
	}
	
	/* (non-Javadoc)
	 * @see domain.ILoginManagement#checkLogin(java.lang.String, java.lang.String)
	 */
	@Override
	public Player checkLogin(String username, String password) throws NotLoggedInException, RemoteException, AlreadyLoggedInException {
		Player result = null;
		for (Player p : this.pManager.getListOfPlayers()) {
			if(p.getName().equals(username) && p.getPassword().equals(password)){
				result = new Player(username, password);
			}
		}
		if(result == null){
			throw new NotLoggedInException();
		} else {
			for (Player p : this.pManager.getCurrentPlayers()) {
				if(username.equals(p.getName())){
					throw new AlreadyLoggedInException();
				}
			}
		}
		this.loggedInPlayers.add(result);
		return result;
	}

	/**
	 * Returns a vector with the loggedin players
	 * @return Vector<Player>
	 */
	public Vector<Player> getLoggedInPlayers() throws RemoteException {
		return this.loggedInPlayers;
	}

	/**
	 * Loads a game
	 * @return IGameManagement
	 */
	public IGameManagement loadGame(Vector<Player> vector, String file)
			throws SaveFileNotFoundException, RemoteException {
		return this.dataFiles.loadGame(vector, file);
	}

	/**
	 * Returns a list of savegames for the logged in players
	 * @return List<String>
	 */
	public List<String> savegames(Vector<Player> currentPlayers)
			throws RemoteException {
		return this.dataFiles.savegames(currentPlayers);
	}
	
}
